package com.team7.happycommunity.propertymanagement.controller;

import com.team7.happycommunity.propertymanagement.common.CommonResult;
import com.team7.happycommunity.propertymanagement.common.LoginToken;
import com.team7.happycommunity.propertymanagement.dto.ResetPwd;
import com.team7.happycommunity.propertymanagement.pojo.PropertyManage;
import com.team7.happycommunity.propertymanagement.service.PropertyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    PropertyService propertyService;

    @GetMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest hr,String username){
        HttpSession s = hr.getSession();
        s.setAttribute("username",username);
        return "测试成功!";
    }

    @PostMapping("/test2")
    @ResponseBody
    public CommonResult test(HttpServletRequest hr){
        return CommonResult.success();
    }

    @RequestMapping("/add")
    @ResponseBody
    public  CommonResult registor(@RequestBody PropertyManage propertyManage){
        Boolean result = propertyService.sign(propertyManage);
        return result?CommonResult.success():CommonResult.failed();
    }

    @PostMapping("/resetpwd")
    @ResponseBody
    public  CommonResult resetpwd(@RequestBody ResetPwd resetPwd){
        boolean success = propertyService.updatePassWord(resetPwd.getOldpass(),resetPwd.getPassword(),resetPwd.getUsername());
        return success?CommonResult.success():CommonResult.failed();
    }

    @RequestMapping("/login")
    @ResponseBody
    public CommonResult<String> login(HttpServletResponse httpServletResponse,@RequestBody PropertyManage propertyManage){
        // 1 . 登录认证
        Boolean veryinfo = propertyService.login(propertyManage);

        // 2 . 存入Cookie信息
        if (veryinfo){
            System.out.println("登录成功");
            LoginToken loginToken = new LoginToken();
            loginToken.setUsername(propertyManage.getUsername());
            return CommonResult.success("登录成功",loginToken);
        }else{
            httpServletResponse.setHeader("status","500");
            return CommonResult.failed();
        }
    }
}
